const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');

const configPath = path.join(__dirname, 'config.json');
const workspaceDir = path.join(__dirname, 'workspace');

function createWorkspaceDir() {
  if (!fs.existsSync(workspaceDir)) {
    fs.mkdirSync(workspaceDir);
  }
}

function pullGitReposFromConfig() {
  try {
    createWorkspaceDir();

    if (fs.existsSync(configPath)) {
      let gitConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
      if (gitConfig.gitRepos && Array.isArray(gitConfig.gitRepos)) {
        syncGitRepos(gitConfig.gitRepos);
      }
    }
  } catch (err) {
    console.error('git代码拉取失败:', err.message);
  }
}

function syncGitRepos(gitRepos, callback) {
  let processed = 0;
  let okRepos = [];
  for (const repoCfg of gitRepos) {
    if (repoCfg.remoteUrl) {
      const repoName = repoCfg.remoteUrl.split('/').pop().replace(/\.git$/, '');
      const repoPath = path.join(workspaceDir, repoName);
      let authUrl = repoCfg.remoteUrl;
      if (repoCfg.username && repoCfg.password) {
        const urlObj = new URL(repoCfg.remoteUrl);
        urlObj.username = repoCfg.username;
        urlObj.password = repoCfg.password;
        authUrl = urlObj.toString();
      }
      if (!fs.existsSync(repoPath)) {
        // clone
        console.log(`(异步) 正在克隆git仓库: ${repoCfg.remoteUrl}`);
        exec(`git clone -b ${repoCfg.branch || 'master'} --depth 1 --filter=blob:none ${authUrl} "${repoPath}"`, (err, stdout, stderr) => {
          if (err) {
            console.error(`克隆仓库失败: ${repoCfg.remoteUrl}`, err.message);
          } else {
            okRepos.push(repoCfg); // 记录已处理的仓库
            console.log(`克隆完成: ${repoCfg.remoteUrl}`);
          }
          if (++processed >= gitRepos.length) {
            callback && callback(null, okRepos);
          }
        });
      } else {
        // pull
        console.log(`(异步) 正在拉取git仓库最新代码: ${repoCfg.remoteUrl}`);
        exec('git pull', { cwd: repoPath }, (err, stdout, stderr) => {
          if (err) {
            console.error(`拉取仓库失败: ${repoCfg.remoteUrl}`, err.message);
          } else {
            okRepos.push(repoCfg); // 记录已处理的仓库
            console.log(`拉取完成: ${repoCfg.remoteUrl}`);
          }
          if (++processed >= gitRepos.length) {
            callback && callback(null, okRepos);
          }
        });
      }
    }
  }
}
module.exports = {
  pullGitReposFromConfig,
  syncGitRepos
};